package com.dsbj.mp.icardservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsbj.common.msg.ResponseMessage;
import com.dsbj.mp.icardservice.entity.Employee;
import com.dsbj.mp.icardservice.entity.EmployeeWelfare;
import com.dsbj.mp.icardservice.entity.Persont;
import com.dsbj.mp.icardservice.model.FunctionModel;
import com.dsbj.mp.icardservice.model.MenuModel;
import com.dsbj.mp.icardservice.model.MenuModelGroup;
import com.dsbj.mp.icardservice.service.EmployeeService;
import com.dsbj.mp.icardservice.service.EmployeeWelfareService;
import com.dsbj.mp.icardservice.service.PersontService;
import com.dsbj.mp.icardservice.service.WxUserService;
import com.dsbj.mp.icardservice.utils.Constants;
import com.dsbj.mp.icardservice.utils.datagene.GeneUUID;
import com.dsbj.mp.icardservice.utils.strprocess.RandomStrUtil;
import com.dsbj.mp.icardservice.utils.strprocess.StrUtil;
import com.dsbj.mp.icardservice.webserviceclient.dsbjpmc.JWSService;
import com.dsbj.mp.icardservice.webserviceclient.dsbjpmc.WxUserResponseMessage;
import com.dsbj.starter.redis.utils.MultiRedisHelper;
import com.dsbj.starter.redis.utils.RedisHelper;
import config.AppConfig;
import lib.MESSAGEXsend;
import lib.MessageSend;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/user")
public class WxUserController extends BaseController {

    @Autowired
    private JWSService jwsService;

    @Autowired
    private WxUserService wxUserService;

    @Autowired
	private RedisHelper redisHelper;

    @Autowired
	private MultiRedisHelper multiRedisHelper;

	@Autowired
	private EmployeeService employeeService;

	@Autowired
	private PersontService persontService;

	@Autowired
	private EmployeeWelfareService employeeWelfareService;

	private List<FunctionModel> functionModelList = new ArrayList<>();

	@Autowired
	private AppConfig appConfig;

	@PostConstruct
	public void init(){
		functionModelList.add(new FunctionModel("访客预约","pages/reservation/list/list","fk.png", Arrays.asList(1)));
		functionModelList.add(new FunctionModel("考勤查询","subpackModule/pages/attendance/monthReport/monthReport","kq.png",Arrays.asList(2,3)));
		functionModelList.add(new FunctionModel("水电查询","pages/reservation/reservation","sd.png",Arrays.asList(2,3)));
		functionModelList.add(new FunctionModel("消费记录","pages/consumeInfo/consumeInfoMonth/consumeInfoMonth","xf.png",Arrays.asList(2,3)));
		functionModelList.add(new FunctionModel("假别额度","pages/restquota/restquota","jb.png",Arrays.asList(2,3)));

		functionModelList.add(new FunctionModel("健康打卡","subpackModule/pages/physicalCondition/list/list","dayhealth.png",Arrays.asList(2,3,4)));
		functionModelList.add(new FunctionModel("员工二维码","subpackModule/pages/physicalCondition/qrcodeEmployee/qrcodeEmployee","qrcode.png",Arrays.asList(2,3,4)));
		functionModelList.add(new FunctionModel("进出登记","subpackModule/pages/physicalCondition/guardCheck/guardCheck","inoutcheck.png",Arrays.asList(4)));
		functionModelList.add(new FunctionModel("消息中心","subpackModule/pages/messagecenter/mcCate/mcCate","remind.png",Arrays.asList(2,3,4)));
		functionModelList.add(new FunctionModel("公司班车","subpackModule/pages/companybus/passenger/passenger","companybus.png",Arrays.asList(2,3,4)));

		functionModelList.add(new FunctionModel("员工推荐","recompackModule/pages/recommend/recommend","ygnj.png",Arrays.asList(2,3)));
	}

	/**
	 * tip: 若未找到wxUser信息，wxUserResponseMessage.status为501。
	 * @deprecated 待删
	 * @param openId
	 * @return
	 */
	@RequestMapping("/getUserByOpenId")
	@Deprecated
    public WxUserResponseMessage getUserByOpenId(String openId){
        return wxUserService.getWxUserByOpenId(openId);
    }

	/**
	 * 获取用户信息V2.0
	 * @param openId
	 * @return
	 */
	@RequestMapping("/getMpUserByOpenId")
	public ResponseMessage getMpUserByOpenId(String openId){
		return wxUserService.getMpUserByOpenId(openId);
	}

	/**
	 * 根据level获取功能菜单。
	 * @deprecated v1.0,已弃用
	 * @param level
	 * @return
	 */
	@Deprecated
	@RequestMapping(value = "/getFunctionModelsByLevel")
	public ResponseMessage getFunctionModelsByLevel(Integer level) {
		List<FunctionModel> functionModels = functionModelList.stream().filter(
				x -> x.getRequireLevelList().contains(level))
				.collect(Collectors.toList());
		return ResponseMessage.ok(functionModels);
	}

	/**
	 * 根据用户身份证号获取功能菜单。
	 *
	 * @param
	 * @return
	 */
	@RequestMapping(value = "/getFunctionModelsByIdcardNo")
	public ResponseMessage getFunctionModelsByIdcardNo(String idcardNo) {
		List<MenuModelGroup> functionModelGroups = wxUserService.getFunctionModelsByIdcardNo(idcardNo);
		return ResponseMessage.ok(functionModelGroups);
	}



	/**
	 * @deprecated 待删
	 * @param type
	 * @param openId
	 * @param username
	 * @param password
	 * @param employeeNo
	 * @param phoneNo
	 * @param vCode
	 * @return
	 */
    @RequestMapping("/wxBindUser")
    @Deprecated
	public ResponseMessage wxBindUser(Integer type, String openId, String username, String password, String employeeNo, String phoneNo, String vCode){
        return wxUserService.wxBindUser(type,openId,username,password,employeeNo, phoneNo, vCode);
    }

	/**
	 * 微信用户绑定V2.0。
	 * @param openId
	 * @param idNo
	 * @param phoneNo
	 * @param vCode
	 * @return
	 */
	@RequestMapping("/mpBindUser")
	public ResponseMessage mpBindUser(String openId, String idNo, String phoneNo, String vCode){
		return wxUserService.mpBindUser(openId,idNo, phoneNo, vCode);
	}

	/**
	 * 获取手机验证码,并且该验证码的有效期为300s。
	 * 传入参数 phoneNo,idcardno。
	 * @param
	 * @return
	 * @author cjw 2019-10-21
	 */
	@RequestMapping(value = "/getVCode")
	public ResponseMessage getVCode(String phoneNo, String idcardno) {
		//解析传来的参数
		if (StringUtils.isBlank(idcardno)) {
			return ResponseMessage.error("身份证号不能为空");
		}
		if (StringUtils.isBlank(phoneNo)) {
			return ResponseMessage.error("手机号不能为空");
		}

		/**
		 * 点击发送短信的时候，先验证身份证是否存在，再验证手机号是否存在
		 */
		//验证身份证号是否存在
		QueryWrapper<Employee> queryWrapper_employee = new QueryWrapper<Employee>()
				.eq("IDCARDNO", idcardno)
				.isNull("DISMISSIONDATE")
				.eq("DELETESTATUS", 1);
		Employee employee = employeeService.getOne(queryWrapper_employee);

		//若人员档案没有该身份证,附加人员信息表取
		if (employee == null) {
			QueryWrapper<Persont> queryWrapper = new QueryWrapper<Persont>()
					.eq("IDCARDNO", idcardno)
					.eq("STATUS", 1);
			Persont persont = persontService.getOne(queryWrapper);
			if (persont == null) {
				return ResponseMessage.error("没有该身份证用户");
			}
			//校验手机号是否一致
			if (StringUtils.isBlank(persont.getPhoneNumber())) {
				return ResponseMessage.error("手机号不存在");
			}
			if (!persont.getPhoneNumber().equals(phoneNo)) {
				return ResponseMessage.error("该身份证用户对应的手机号不一致");
			}
		} else {
			/**
			 * 若人员档案有该身份证,从附加信息表查出手机号，检验是否一致
			 */
			QueryWrapper<EmployeeWelfare> queryWrapper_employeeWelfare = new QueryWrapper<EmployeeWelfare>()
					.eq("EMPLOYEENO", employee.getEmployeeno());
			EmployeeWelfare employeeWelfare = employeeWelfareService.getOne(queryWrapper_employeeWelfare);
			if (null == employeeWelfare) {
				return ResponseMessage.error("人员附加信息不存在");
			}
			if (StringUtils.isBlank(employeeWelfare.getContactway())) {
				return ResponseMessage.error("手机号不存在");
			}
			if (!employeeWelfare.getContactway().equals(phoneNo)) {
				return ResponseMessage.error("该身份证用户对应的手机号不一致");
			}
		}


		/**
		 * 发送验证码短信。分析该手机号对应的验证码是否已存在。
		 */
		String key = Constants.WX_BIND_VCODE_PREFIX + phoneNo;
		String vcodeRedis = (String) multiRedisHelper.get(key, Constants.REDISDB_VCODE);
		int limit = Constants.EXPIRE_WX_BIND_CODE / 60;
		if (StringUtils.isNotBlank(vcodeRedis)) {
			//若验证码未失效,直接发送短信
			logger.info("验证码未失效 vcodeRedis=" + vcodeRedis+"; phoneNo="+phoneNo);
			MESSAGEXsend messageXsend = new MESSAGEXsend(appConfig);
			messageXsend.addTo(phoneNo);
			messageXsend.setProject("g749D");
			messageXsend.addVar("code", vcodeRedis);
			messageXsend.addVar("limit", String.valueOf(limit));
			messageXsend.xsend();
		} else {
			//产生6位数字验证码,发送验证码短信,并将该验证码存入redis缓存中,其有效期为300s。
			String vcode = RandomStrUtil.getNumStr(6);
			logger.info("生成验证码 vcode=" + vcode);

			MESSAGEXsend messageXsend = new MESSAGEXsend(appConfig);
			messageXsend.addTo(phoneNo);
			messageXsend.setProject("g749D");
			messageXsend.addVar("code", vcode);
			messageXsend.addVar("limit", String.valueOf(limit));
			messageXsend.xsend();
			multiRedisHelper.set(Constants.WX_BIND_VCODE_PREFIX + phoneNo, vcode, Constants.EXPIRE_WX_BIND_CODE, Constants.REDISDB_VCODE);
		}
		return ResponseMessage.ok();
	}

    @RequestMapping("/getOpenIdByCode")
    public ResponseMessage getOpenIdByCode(String code){
        return wxUserService.getOpenIdByCode(code);
    }

	/**
	 * 获取可订阅消息的模板id列表。
	 * @deprecated 待删 已舍弃
	 * @param
	 * @return
	 * @author cjw 2020-02-17
	 */
	@Deprecated
	@RequestMapping(value = "/getMsgTemplateId")
	public ResponseMessage getMsgTemplateId() {

		List<String> list_templateId = new ArrayList<>();
		//打卡提醒
		list_templateId.add("XrFHJDuU0hfVJcuPARCNje4U_C34lfulRVNh3rQFEPY");

		//返回的消息体
		Map<String, Object> mapReturn = new LinkedHashMap<>();
		mapReturn.put("templateIds",list_templateId);
		return ResponseMessage.ok(mapReturn);
	}


}
